<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="车间名称" prop="wkspName">
        <el-input v-model="queryParams.wkspName" placeholder="请输入车间名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="车间任务编码" prop="wkspCode">
        <el-input v-model="queryParams.wkspCode" placeholder="请输入车间任务编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="计划生产数量" prop="wkspPlanQuantity">
        <el-input v-model="queryParams.wkspPlanQuantity" placeholder="请输入计划生产数量" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="overTime">
        <el-date-picker style="width: 190px;" clearable v-model="queryParams.overTime" type="date"
          value-format="yyyy-MM-dd" placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.mes_wksp_task_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:task:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:task:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:task:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:task:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="" align="center" prop="id" /> -->
      <!-- <el-table-column label="车间名称" align="center" prop="wkspName" /> -->
      <el-table-column label="任务状态" align="center" prop="operationStatus">
        <template slot-scope="scope">
          <el-tag :type="tagtype(scope.row.operationStatus)" effect="dark">
            <dict-tag :options="dict.type.mes_wksp_task_status" :value="scope.row.operationStatus" />
          </el-tag>

        </template>
      </el-table-column>
      <el-table-column label="领料状态" align="center" prop="pickingStatus">
        <template slot-scope="scope">
          <el-tag :type="tagtype(scope.row.pickingStatus)" effect="dark">
            <dict-tag :options="dict.type.mes_picking_status" :value="scope.row.pickingStatus" />
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="生产进度" align="center" width="250">
        <template slot-scope="scope">
          <el-progress :text-inside="true" :color="customColorMethod(scope.row.productionSchedule)" :stroke-width="20"
            :percentage="scope.row.productionSchedule" status="exception"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="车间任务编码" align="center" prop="wkspCode" width="150" />
      <el-table-column label="产品名称" align="center" prop="proInfo.proName" width="150" />
      <el-table-column label="产品编码" align="center" prop="proInfo.proCode" width="150" />
      <el-table-column label="计划生产数量" align="center" prop="wkspPlanQuantity" width="150" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="overTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.overTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售订单编号" align="center" prop="proOrder.orderNumber" width="150" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" width="180" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.pickingStatus == 0" size="mini" type="text" icon="el-icon-edit"
            @click="pickingList(scope.row)" v-hasPermi="['mes:task:edit']">领料申请</el-button>
          <el-button v-else-if="scope.row.pickingStatus == 2 && scope.row.operationStatus == 0" size="mini" type="text"
            icon="el-icon-edit" @click="shengcheng(scope.row)" v-hasPermi="['mes:task:edit']">生成任务卡</el-button>

          <el-button v-if="scope.row.operationStatus == 1" size="mini" type="text" icon="el-icon-edit"
            @click="revokeTaskCart(scope.row)" v-hasPermi="['mes:task:edit']">撤回任务卡</el-button>

          <el-button v-if="scope.row.operationStatus == 0" size="mini" type="text" icon="el-icon-delete"
            @click="deleteWskpTask(scope.row)" v-hasPermi="['mes:task:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <el-dialog title="生成任务卡" :visible.sync="timesetopen" width="500px" append-to-body>
      <div style="margin: 10px;">
        <label style="background-color: rgb(117, 208, 248);padding: 5px;border-radius: 7px;margin-right: 10px;">每卡产品数量:</label>
        <el-input-number size="mini" v-model="splitQuantity" :min="1" :max="nowData.wkspPlanQuantity"></el-input-number>
      </div>
      <div style="margin: 10px;">
        <label style="background-color: rgb(117, 208, 248);padding: 5px;border-radius: 7px;margin-right: 10px;">任务开始时间:</label>
        <el-date-picker v-model="startTime" type="date" placeholder="选择任务开始日期" format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </div>

      <div style="margin: 10px;">
        <label style="background-color: rgb(117, 208, 248);padding: 5px;border-radius: 7px;margin-right: 10px;">任务结束时间:</label>

        <el-date-picker v-model="overTime" type="date" placeholder="选择任务结束日期" format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </div>



      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createTaskCard()">确 定</el-button>
        <el-button @click="cancel()">取 消</el-button>
      </div>
    </el-dialog>




    <!-- 领料清单 -->
    <el-dialog title="领料清单" :visible.sync="pickingListopen" width="700px" append-to-body>
      <el-card style="border-radius: 15px;background-color: rgba(191, 185, 176, 0.687);" shadow="always">
        <el-table :data="pickingListData.mtrs" border style="width: 100%;border-radius: 15px;">
          <el-table-column prop="mtrName" align="center" label="物料名称">
          </el-table-column>
          <el-table-column prop="mtrCode" align="center" label="物料编码">
          </el-table-column>
          <el-table-column prop="mtrQuantity" align="center" label="领料数量">
          </el-table-column>
        </el-table>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="applyFor()">申 请 领 料</el-button>
        <el-button @click="cancel()">取 消</el-button>
      </div>
    </el-dialog>






    <!-- 添加或修改车间任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车间名称" prop="wkspName">
          <el-input v-model="form.wkspName" placeholder="请输入车间名称" />
        </el-form-item>
        <el-form-item label="车间任务编码" prop="wkspCode">
          <el-input v-model="form.wkspCode" placeholder="请输入车间任务编码" />
        </el-form-item>
        <el-form-item label="计划生产数量" prop="wkspPlanQuantity">
          <el-input v-model="form.wkspPlanQuantity" placeholder="请输入计划生产数量" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="overTime">
          <el-date-picker clearable v-model="form.overTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in dict.type.mes_wksp_task_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, pickingList, confirmPicking, start, revokeTaskCart, deleteWskpTask } from "@/api/mes/task";

export default {
  name: "Task",
  dicts: ['mes_wksp_task_status', 'mes_picking_status'],
  data() {
    return {
      //拆卡数量
      splitQuantity: null,
      //任务结束时间
      overTime: "",
      //任务开始时间
      startTime: "",
      //生成任务卡时间设置对话框
      timesetopen: false,
      //当前点击记录id
      nowid: "",
      //当前点击记录信息
      nowData: "",
      //领料清单数据
      pickingListData: [],
      //领料清单对话框
      pickingListopen: false,
      //生产进度
      productionSchedule: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车间任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wkspName: null,
        wkspCode: null,
        wkspPlanQuantity: null,
        startTime: null,
        overTime: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //删除车间任务卡
    deleteWskpTask(row) {
      deleteWskpTask({ id: row.id }).then(res => {
        this.$notify({
          title: '成功',
          message: '删除成功！',
          type: 'success',
          position: 'top-left'
        });
        this.getList()
      })
    },
    //撤回任务卡
    revokeTaskCart(row) {
      revokeTaskCart({ id: row.id }).then(res => {
        // this.$modal.msgSuccess("撤回成功！");
        this.$notify({
          title: '成功',
          message: '撤回成功！',
          type: 'success',
          position: 'top-left'
        });
        this.getList()
      })
    },
    //生成任务卡
    createTaskCard() {
      if (this.startTime == "" || this.overTime == "") {
        // this.$modal.msgError("请选择任务开始时间或结束时间");
        this.$notify({
          title: '错误',
          message: '请选择任务开始时间或结束时间',
          type: 'error',
          position: 'top-left'
        });
      } else if (new Date(this.startTime) > new Date(this.overTime)) {
        // this.$modal.msgError("开始时间大于结束时间");
        this.$notify({
          title: '错误',
          message: '开始时间大于结束时间',
          type: 'error',
          position: 'top-left'
        });
      } else {
        start({ id: this.nowid, startTime: this.startTime, overTime: this.overTime, splitQuantity: this.splitQuantity }).then(res => {
          // this.$modal.msgSuccess("任务卡生成成功！");
          this.$notify({
            title: '成功',
            message: '任务卡生成成功！',
            type: 'success',
            position: 'top-left'
          });
          this.timesetopen = false
          this.getList()
        })
      }

    },
    //生成任务卡按钮
    shengcheng(row) {
      this.timesetopen = true
      this.nowid = row.id
      this.nowData = row
    },
    //申请领料
    applyFor() {
      confirmPicking({ id: this.nowid }).then(res => {
        // this.$modal.msgSuccess("申请成功！");
        this.$notify({
          title: '成功',
          message: '申请成功！',
          type: 'success',
          position: 'top-left'
        });
        this.getList()
        this.pickingListopen = false
      })
    },
    //领料清单
    pickingList(row) {
      this.nowid = row.id
      pickingList({ id: row.id }).then(res => {
        console.log("🚀 ~ file: index.vue:201 ~ pickingList ~ res:", res)
        this.pickingListData = res.data;
        this.pickingListopen = true

      })
    },
    //标签颜色控制
    tagtype(data) {
      switch (data) {
        case 0:
          return "info"
        case 1:
          return "warning"
        case 2:
          return "success"
        case 3:
          return "danger"
      }
    },
    //进度条颜色控制
    customColorMethod(data) {
      if (data < 30) {
        return '#f56c6c'
      } else if (data < 100) {
        return '#e6a23c';
      } else {
        return '#67c23a';
      }
    },
    /** 查询车间任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.pickingListopen = false
      this.timesetopen = false
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        progId: null,
        wkspName: null,
        wkspCode: null,
        wkspPlanQuantity: null,
        wkspReadyQuantity: null,
        startTime: null,
        overTime: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车间任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改车间任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除车间任务编号为"' + ids + '"的数据项？').then(function () {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
